export class CookieTool {
  /**
   * 设置 cookie
   *
   * @param name - cookie 名称
   * @param value - cookie 值
   * @param expDays - cookie 过期天数，默认30天
   */
  set(name: string, value: string, expDays: number = 30): void {
    const d = new Date()
    d.setTime(d.getTime() + expDays * 24 * 60 * 60 * 1000)
    const expires = 'expires=' + d.toUTCString()
    document.cookie = `${name}=${encodeURIComponent(value)}; ${expires}; path=/`
  }

  /**
   * 获取 cookie
   *
   * @param name - cookie 名称
   * @returns cookie 值 或 空字符串如果未找到
   */
  get(name: string): string {
    const cookies = document.cookie.split('; ')
    for (const cookie of cookies) {
      const [cookieName, cookieValue] = cookie.split('=')
      if (cookieName === name) {
        return decodeURIComponent(cookieValue || '')
      }
    }
    return ''
  }

  /**
   * 删除 cookie
   *
   * @param name - cookie 名称
   */
  delete(name: string): void {
    this.set(name, '', -1)
  }

  /**
   * 移除 cookie（与 delete 方法相同）
   *
   * @param name - cookie 名称
   */
  remove(name: string): void {
    this.delete(name)
  }
}
